import { Message, MessageBox } from "element-ui";

let _ = require("lodash");

let moment = require("moment");
// 中文简体
moment.locale("zh-cn");

export function getDataTime(time: string, format: string) {
  if (format == "") {
    format = "YYYY-MM-DD HH:mm:ss";
  }
  return moment(time).format(format); //2019-07-10 09:15:18
}

export function message(data: { state: number; msg: string }) {
  if (data.state && data.state === 1) {
    if (_.isEmpty(data.msg)) {
      data.msg = "操作成功";
    }
    Message.success({ message: data.msg });
  } else if (data.state && data.state === 0) {
    if (_.isEmpty(data.msg)) {
      data.msg = "操作失败";
    }
    Message.error({ message: data.msg });
  } else {
    if (_.isEmpty(data.msg)) {
      data.msg = "以响应";
    }
    Message.info({ message: data.msg });
  }
}

interface messageBox {
  msg: "";
  btn1: "确定";
  btn2: "取消";
}

export function messageBox(
  param: messageBox,
  success: Function = function() {},
  error: Function = function() {}
) {
  MessageBox.confirm(param.msg, "提示", {
    confirmButtonText: param.btn1,
    cancelButtonText: param.btn2,
    type: "warning"
  })
    .then(() => {
      if (success) {
        success();
      }
    })
    .catch(() => {
      if (error) {
        error();
      }
    });
}

export function alert(
  message: string,
  title: string,
  callback: Function = function() {}
) {
  MessageBox.alert(message, title, {
    confirmButtonText: "确定",
    callback: action => {
      if (callback) {
        callback();
      }
    }
  });
}

/**
 * 表单赋值
 * @param form
 * @param param
 */
export function formInitialize(form: any, param: any) {
  let key = keys(form);
  if (key[1].length > 0) {
    key[1].forEach((item: any, index: number) => {
      form[item] = param[_.split(item, ".")[0]][_.split(item, ".")[1]];
    });
  }
  param = _.pick(param, key[0]);
  param = _.omitBy(param, _.isNull);
  return _.defaultsDeep(param, form);
}

function keys(form: {}) {
  const key = _.keys(form);
  let temp = [];
  let one: any = [];
  let two: any = [];
  key.forEach((item: any, index: number) => {
    if (_.split(item, ".").length === 1) {
      one.push(item);
    } else {
      two.push(item);
    }
  });
  temp.push(one);
  temp.push(two);
  return temp;
}

export default {
  message,
  messageBox,
  alert,
  /**
   * 表单赋值
   */
  formInitialize,
  /**
   * 时间处理
   */
  getDataTime
};
